package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.AnswerDaoIF;
import de.hhbk.feedbackmodul.entities.Answer;

@Stateless
public class AnswerDaoBean implements AnswerDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());
	

	@SuppressWarnings("unchecked")
	@Override
	public List<Answer> getAllAnswers() throws Exception  {
		try
		{
			Query query = manager.createQuery("select a from Answer a", Answer.class);
			return (List<Answer>) query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading Answers: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void createAnswer(Answer answer) throws Exception {
		try
		{
			manager.persist(answer);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting Answer: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void updateAnswer(Answer answer) throws Exception {
		try
		{
			manager.merge(answer);
		}
		catch(Exception e)
		{
			logger.error("Error while updating Answer: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void deleteAnswer(Answer answer) throws Exception {
		try
		{
			Answer answerToDelete = manager.find(Answer.class, answer.getId());
			manager.remove(answerToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting Answer: "+e.getMessage(), e);
			throw e;
		}
	}

}
